﻿/// <summary>
/// 
///	Author:		    Gerard Finn
///
///	Student No		X00115840
///
///	Date:			Start Date 	:- 22-03-2014
///	Modified					:-
/// 
/// File            ProcessUserSelection.cs
///   
///	Description		Client section for connecting to the web service
///
/// </summary>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Client
{
    /// <summary>
    /// 
    ///   Class for dealing with connection to Azure cloud
    ///   
    /// </summary>
    public class ProcessUserSelection
    {
        HttpClient webClient = new HttpClient();
        /// <summary>
        /// 
        ///     Pre     :- None
        ///                
        ///     Post    :- on exit the database has been opened or an exception has been throwen
        ///     
        /// </summary>
        public ProcessUserSelection()
        {
            StockData = new StockDetails();
            try
            {
//                webClient.BaseAddress = new Uri("http://localhost:1045/");  // base URL for API Controller
                webClient.BaseAddress = new Uri("http://gfinnx00115840ca1.cloudapp.net/");  // URL API Controller in Azure cloud
//                webClient.BaseAddress = new Uri("http://gfinnx00115840ca1.azurewebsites.net/");

                // add an Accept header for JSON
                webClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                // add an Accept header for XML
                webClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
                webClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));

                webClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
                webClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/text"));
            }
            catch ( Exception e )
            {
                IOClass.WriteLine( LocalisationSettings.GetString("HostConnectionExceptionString") + "\n" + e.ToString());
            }
        }
        /// <summary>
        /// 
        ///  Make a stock data element with things to change
        /// 
        /// </summary>
        public StockDetails StockData
        {
            get;
            private set;
        }
        /// <summary>
        /// 
        ///  This string will contain any error mesaages obtained from the functions run
        ///  
        /// </summary>
        public String ErrorMessage
        {
            get;
            set;
        }
        /// <summary>
        /// 
        ///  This string will contain the mesaages obtained from a successfull functions run
        ///  
        /// </summary>
        public String SuccessMessage
        {
            get;
            set;
        }
        /// <summary>
        /// 
        ///     Pre     :- The database connection must be open
        ///     
        ///     Post    :- returns true if data has been obtained
        ///     
        /// </summary>
        public bool getAllItems()
        {
            try
            {
                HttpResponseMessage response = webClient.GetAsync(LocalisationSettings.GetString("APIServiceString")).Result;

                //Console.WriteLine(response);
                //Console.ReadLine();
                if (response.IsSuccessStatusCode)                                    // 200 to 299 are success codes
                {
                    // read results
                    var listings = response.Content.ReadAsAsync<IEnumerable<StockDetails>>().Result;
                    //
                    // Display all data returned
                    //
                    foreach (var listing in listings)
                    {
                        this.SuccessMessage = listing.ProductIdSymbol + " " +
                                              listing.ProductNameSymbol + " " +
                                              listing.PurchacePrice + " " +
                                              listing.SalesPrice + " " +
                                              listing.CurrentStockLevel + " " +
                                              listing.StartingStockLevel + "\n";
                    }
                    return true;
                }
                else
                {
                    this.ErrorMessage = LocalisationSettings.GetString("UnableToGetAnyDataString")
                                        + "\n"
                                        + LocalisationSettings.GetString("StatusCodeString")
                                        + response.StatusCode + " " + response.ReasonPhrase;
                    return false;
                }
            }
            catch(Exception e)
            {
                this.ErrorMessage = e.ToString();
                return false;
            }

        }
        /// <summary>
        /// 
        ///     Pre     :- The database connection must be open
        ///                Input is a valid name for an item in the database
        ///                
        ///     Post    :- returns true if data has been obtained else false
        ///     
        /// </summary>
        public bool getSingleItem(String productIdSymbol)
        {
            try
            {
                HttpResponseMessage response = webClient.GetAsync(LocalisationSettings.GetString("APIServiceString") 
                                                                  +  "/" 
                                                                  +  productIdSymbol
                                                                  ).Result;

                if (response.IsSuccessStatusCode)
                {
                    //  everything else is causing an exception 
                    //                    double retList = response.Content.ReadAsAsync<double>().Result;
                    //                    Console.WriteLine(retList);

                    var listings = response.Content.ReadAsAsync<IEnumerable<StockDetails>>().Result;

                    foreach (var strList in listings)
                    {
                        if (productIdSymbol.ToUpper() == strList.ProductIdSymbol.ToString().ToUpper())
                        {
                            this.SuccessMessage = strList.ProductIdSymbol + " " +
                                                  strList.ProductNameSymbol + " " +
                                                  strList.PurchacePrice + " " +
                                                  strList.SalesPrice + " " +
                                                  strList.CurrentStockLevel + " " +
                                                  strList.StartingStockLevel + "\n";
                            //
                            // Assign to the local StockDetails variable
                            //
                            StockData = strList;
                            return true;
                        }
                    }
                    return false;
                }
                else
                {
                            this.ErrorMessage = LocalisationSettings.GetString("UnableToGetSelectedItemString") + productIdSymbol
                                                                                + "\n"
                                                                                + LocalisationSettings.GetString("StatusCodeString")
                                                                                + response.StatusCode + " " + response.ReasonPhrase;
                            return false;
                }
            }
            catch (Exception e)
            {
                this.ErrorMessage = e.ToString();
                return false;
            }
        }
        /// <summary>
        /// 
        ///     Pre     :- The database connection must be open
        ///                Input is a name to input into the database
        ///                
        ///     Post    :- returns true if the name has been modified else false
        ///     
        /// </summary>
        public bool putSingleItem(String productIdSymbol)
        {
            // Just overwrite all elements with default details bar id
            //
            StockDetails data = new StockDetails();
            data.ProductIdSymbol = productIdSymbol;
            try
            {
                HttpResponseMessage response = webClient.PutAsJsonAsync(LocalisationSettings.GetString("APIServiceString")
                                                                        + "/"
                                                                        + productIdSymbol
                                                                        , data
                                                                        ).Result;
                if (!response.IsSuccessStatusCode)
                {
                    this.ErrorMessage = LocalisationSettings.GetString("UnableToModifyItemString") + productIdSymbol + "\n"
                                        + response.StatusCode + " " + response.ReasonPhrase;
                    return false;
                }
                this.SuccessMessage = LocalisationSettings.GetString("ItemModifyedString") + productIdSymbol;
                // Deleted item from data base
                return true;
            }
            catch (Exception e)
            {
                this.ErrorMessage = e.ToString();
                return false;
            }
        }
        /// <summary>
        /// 
        ///     Pre     :- The database connection must be open
        ///                Input is a name to input into the database
        ///                
        ///     Post    :- returns true if the element has been modified else false
        ///     
        /// </summary>
        public bool putSingleItem( StockDetails data )
        {
            try
            {
                HttpResponseMessage response = webClient.PutAsJsonAsync(LocalisationSettings.GetString("APIServiceString") 
                                                                        + "/"
                                                                        + data.ProductIdSymbol
                                                                        , data
                                                                        ).Result;
                if (!response.IsSuccessStatusCode)
                {
                    this.ErrorMessage = LocalisationSettings.GetString("UnableToModifyItemString") 
                                        + data.ProductIdSymbol 
                                        + "\n"
                                        + response.StatusCode 
                                        + " " 
                                        + response.ReasonPhrase;
                    return false;
                }
                this.SuccessMessage = LocalisationSettings.GetString("ItemModifyedString") + data.ProductIdSymbol;
                // Deleted item from data base
                return true;
            }
            catch (Exception e)
            {
                this.ErrorMessage = e.ToString();
                return false;
            }
        }
        /// <summary>
        /// 
        ///     Pre     :- The database connection must be open
        ///                Input is a valid name in the database
        ///                
        ///     Post    :- returns true if something has been added else false
        ///     
        /// </summary>
        public bool postSingleItem(String productIdSymbol)
        {
            // Just adding a new element with default details bar id
            //
            StockDetails data = new StockDetails();
            data.ProductIdSymbol = productIdSymbol;

            // Dont duplicate the code just use the other function
            //
            if (!postItemStockData(data))
            {
                this.ErrorMessage = LocalisationSettings.GetString("UnableToAddItemString") + productIdSymbol;
                return false;
            }
            return true;
        }
        /// <summary>
        /// 
        ///     Pre     :- The database connection must be open
        ///                Data is a valid name in the database and contains other details
        ///                
        ///     Post    :- returns true if something has been added else false
        ///     
        /// </summary>
        public bool postItemStockData(StockDetails data)
        {
            try
            {
                HttpResponseMessage response = webClient.PostAsJsonAsync(LocalisationSettings.GetString("APIServiceString")
                                                                          , data).Result;
                if (response.IsSuccessStatusCode)
                {
                    Uri newStockUri = response.Headers.Location;

                    this.SuccessMessage = LocalisationSettings.GetString("NewURIResourceString") + newStockUri.ToString();
                    return true;
                }
                this.ErrorMessage = LocalisationSettings.GetString("URINotAddedString") 
                                    + data.ProductIdSymbol 
                                    + "\n" 
                                    + response.StatusCode.ToString()
                                    + " "
                                    + response.ReasonPhrase.ToString();

                // Unable to add item from data base
                return false;
            }
            catch (Exception e)
            {
                this.ErrorMessage = e.ToString();
                return false;
            }
        }
        /// <summary>
        /// 
        ///     Pre     :- The database connection must be open
        ///                Input is a valid name for an item in the database
        ///                
        ///     Post    :- returns true if item has been deleted else false
        ///     
        /// </summary>
        public bool deleteItem(String productIdSymbol)
        {
            try
            {
                HttpResponseMessage response = webClient.DeleteAsync(LocalisationSettings.GetString("APIServiceString")
                                                                        + "/"
                                                                        + productIdSymbol
                                                                        ).Result;
                if (!response.IsSuccessStatusCode)
                {
                    IOClass.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
                    this.ErrorMessage = LocalisationSettings.GetString("UnableToDeleteItemString") + productIdSymbol + "\n"
                                        + response.StatusCode + " " + response.ReasonPhrase;
                    return false;
                }
                this.SuccessMessage = LocalisationSettings.GetString("DeletedItemFromDB") + productIdSymbol;
                // Deleted item from data base
                return true;
            }
            catch (Exception e)
            {
                this.ErrorMessage = e.ToString();
                return false;
            }
        }

    }       // End of class ProcessUserSelection

}           // End of namespace
